import {
  Controller,
  Get,
  Post,
  Body,
  Param,
  Delete,
  Request,
  UseGuards,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { CommentsService } from './comments.service';
import { Comment } from './comment.entity';

@Controller('comments')
export class CommentsController {
  constructor(private readonly commentsService: CommentsService) {}

  // 添加评论
  @UseGuards(AuthGuard('jwt'))
  @Post()
  async addComment(@Request() req, @Body() commentData: { postId: number; content: string }) {
    try {
      const userId = parseInt(req.user.id);
      const comment = await this.commentsService.addComment(
        userId,
        commentData.postId,
        commentData.content,
      );
      return {
        success: true,
        data: comment,
        message: '评论成功',
      };
    } catch (error) {
      return {
        success: false,
        data: null,
        message: '评论失败: ' + error.message,
      };
    }
  }

  // 获取动态的所有评论
  @UseGuards(AuthGuard('jwt'))
  @Get('post/:postId')
  async getCommentsByPostId(@Param('postId') postId: string) {
    try {
      const comments = await this.commentsService.getCommentsByPostId(parseInt(postId));
      return {
        success: true,
        data: comments,
        message: '获取评论成功',
      };
    } catch (error) {
      return {
        success: false,
        data: [],
        message: '获取评论失败: ' + error.message,
      };
    }
  }

  // 删除评论
  @UseGuards(AuthGuard('jwt'))
  @Delete(':id')
  async deleteComment(@Request() req, @Param('id') id: string) {
    try {
      const userId = parseInt(req.user.id);
      const result = await this.commentsService.deleteComment(userId, parseInt(id));
      if (!result) {
        return {
          success: false,
          data: null,
          message: '评论不存在或无权限删除',
        };
      }
      return {
        success: true,
        data: null,
        message: '评论删除成功',
      };
    } catch (error) {
      return {
        success: false,
        data: null,
        message: '评论删除失败: ' + error.message,
      };
    }
  }
}